import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:panda/base/SignType.dart';
import 'package:panda/base/application.dart';
import 'package:panda/entity/good_list_entity.dart';
import 'package:panda/goods/GoodsDetail.dart';
import 'package:panda/goods/SharePinPaiPic.dart';
import 'package:panda/goods_by_cat_list/BrandList.dart';
import 'package:panda/http/Api.dart';
import 'package:panda/http/HttpUtil.dart';
import 'package:panda/util/AppSaveInfoUtil.dart';
import 'package:panda/util/LoadingUtil.dart';
import 'package:panda/util/SignUtil.dart';

import '../base/Constant.dart';

class PinPaiListPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return PinPaiListView();
  }
}

class PinPaiListView extends State<PinPaiListPage> {
  List<GoodsListDataData> goodsList = new List();
  int page = 1;
  String group_id = "1";
  String name = "";
  String token = "";
  EasyRefreshController _controller = EasyRefreshController();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getString(TOKEN).then((value) {
      token = value;
      // loadList();
    });
    if (APPLIC.userInfoMap != null)
      group_id = APPLIC.userInfoMap['user_msg']['group_id'].toString();
    loadList();
  }

  loadList() async {
    Map map = new Map();
    map['p'] = page.toString();
    map['per'] = "50";
    map['name'] = name;
    map['sign_type'] = SignType.GET_GOODS_LIST;
    Response<String> response = await HttpUtil().post(
        Api.BaseUrl + "/index.php/wap/GoodsBrand/getList",
        data: getSign(map));
    Map userMap = json.decode(response.data);
    if (userMap['code'] == 1 && mounted) {
      GoodsListEntity bannerEntity = new GoodsListEntity.fromJson(userMap);
      setState(() {
        if (page == 1) {
          goodsList.clear();
        }
        if (page == 1) {
          _controller.resetLoadState();
          _controller.finishRefresh();
        } else {
          _controller.finishLoad(
              success: true, noMore: bannerEntity.data.datas.length == 0);
          if (bannerEntity.data.datas.length == 0) {
            Fluttertoast.showToast(msg: "已加载全部");
          }
        }
        goodsList.addAll(bannerEntity.data.datas);
        setState(() {});
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);

    return new Scaffold(
      appBar: new AppBar(
        title: Text("品牌馆",
            style: TextStyle(
                fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE),
                color: Colors.black)),
        backgroundColor: Colors.white,
        brightness: Brightness.light,
        centerTitle: true,
        iconTheme: new IconThemeData(color: Colors.black),
        elevation: 0.5,
      ),
      body: new Container(
        color: white,
        child: Column(
          children: <Widget>[
            Container(
              padding: EdgeInsets.all(10),
              color: f0Color,
              child: Row(
                children: <Widget>[
                  Expanded(
                    flex: 1,
                    child: Container(
                      margin: EdgeInsets.fromLTRB(
                          ScreenUtil.getInstance().setHeight(DP_10),
                          0,
                          ScreenUtil.getInstance().setHeight(DP_10),
                          0),
                      height: ScreenUtil.getInstance().setHeight(DP_60),
                      decoration: BoxDecoration(
                          color: white,
                          borderRadius: BorderRadius.circular(20.0)),
                      child: ConstrainedBox(
                        constraints: BoxConstraints(maxHeight: DP_80),
                        child: TextField(
                          keyboardAppearance: Brightness.light,
                          maxLines: 1,
                          onChanged: (value) {
                            name = value;
                          },
                          cursorColor: mainColor,
                          decoration: new InputDecoration(
                              // contentPadding: EdgeInsets.all(0),
                              prefixIcon: Icon(
                                Icons.search,
                                color: Colors.black45,
                              ),
                              hintText: "搜索品牌",
                              border: InputBorder.none,
                              hintStyle: TextStyle(
                                  color: Colors.black45,
                                  fontSize: ScreenUtil.getInstance()
                                      .setSp(NORMAL_FONT_SIZE))),
                        ),
                      ),
                    ),
                  ),
                  GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    child: Container(
                        decoration: BoxDecoration(
                            // color: mainColor,
                            borderRadius: BorderRadius.circular(15)),
                        alignment: Alignment.center,
                        padding: EdgeInsets.all(5),
                        width: ScreenUtil.getInstance().setWidth(DP_80 + 50),
                        child: Text('搜索',
                            style: TextStyle(
                                color: black_99,
                                fontSize: ScreenUtil.getInstance()
                                    .setSp(NORMAL_FONT_SIZE)))),
                    onTap: () {
                      page = 1;
                      loadList();
                    },
                  )
                ],
              ),
            ),
            Expanded(
                child: new EasyRefresh(
              enableControlFinishRefresh: true,
              enableControlFinishLoad: true,
              header: MaterialHeader(),
              footer: MaterialFooter(),
              controller: _controller,
              child: ListView.builder(
                  itemBuilder: _renderRow, itemCount: goodsList.length),
              onRefresh: () async {
                page = 1;
                loadList();
              },
              onLoad: () async {
                page++;
                loadList();
              },
            ))
          ],
        ),
      ),
    );
  }

  Widget _renderRow(BuildContext context, int index) {
    return GestureDetector(
      child: Container(
        margin: EdgeInsets.fromLTRB(
            ScreenUtil.getInstance().setHeight(DP_20),
            ScreenUtil.getInstance().setHeight(DP_20),
            ScreenUtil.getInstance().setHeight(DP_20),
            0),
        decoration: BoxDecoration(
            color: white,
            borderRadius: BorderRadius.circular(
                ScreenUtil.getInstance().setHeight(DP_10))),
        child: Material(
          borderRadius:
              BorderRadius.circular(ScreenUtil.getInstance().setHeight(DP_10)),
          color: white,
          child: new Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              ClipRRect(
                borderRadius: BorderRadius.only(
                    topRight: Radius.circular(
                        ScreenUtil.getInstance().setHeight(DP_10)),
                    topLeft: Radius.circular(
                        ScreenUtil.getInstance().setHeight(DP_10))),
                child: CachedNetworkImage(
                    imageUrl: Api.ImgBaseUrl + goodsList[index].logo,
                    width: MediaQuery.of(context).size.width -
                        ScreenUtil.getInstance().setHeight(DP_40),
                    fit: BoxFit.fill,
                    height: (MediaQuery.of(context).size.width -
                            ScreenUtil.getInstance().setHeight(DP_40)) *
                        2 /
                        4),
              ),
              Container(
                padding: EdgeInsets.fromLTRB(
                    ScreenUtil.getInstance().setHeight(DP_15),
                    ScreenUtil.getInstance().setHeight(DP_15),
                    ScreenUtil.getInstance().setHeight(DP_15),
                    ScreenUtil.getInstance().setHeight(DP_8)),
                child: Row(
                  children: <Widget>[
                    Text(
                      goodsList[index].rate,
                      style: TextStyle(
                          fontSize: ScreenUtil.getInstance()
                              .setSp(NORMAL_FONT_SIZE + 20),
                          color: mainColor),
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                    Expanded(
                        child: Text(
                      goodsList[index].description,
                      style: TextStyle(
                          fontSize: ScreenUtil.getInstance()
                              .setSp(NORMAL_FONT_SIZE + 5),
                          color: black),
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    )),
                    GestureDetector(
                      child: Container(
                        padding: EdgeInsets.fromLTRB(8, 3, 8, 3),
                        decoration: BoxDecoration(
                            color: mainColor,
                            borderRadius: BorderRadius.circular(15)),
                        child: Row(
                          children: <Widget>[
                            Icon(
                              Icons.share,
                              color: white,
                              size: 15,
                            ),
                            Text(
                              "分享",
                              style: TextStyle(
                                  fontSize: ScreenUtil.getInstance()
                                      .setSp(NORMAL_FONT_SIZE),
                                  color: white),
                              maxLines: 2,
                              overflow: TextOverflow.ellipsis,
                            )
                          ],
                        ),
                      ),
                      onTap: () {
                        showDialog(
                            context: context,
                            barrierDismissible: false,
                            builder: (_) {
                              return new NetLoadingDialog(
                                loadingText: "准备素材...",
                                bgColor: Color.fromARGB(255, 0, 0, 0),
                                requestCallBack: null,
                                outsideDismiss: false,
                              );
                            });
                        loadList2(
                            goodsList[index].brand_id,
                            goodsList[index].description,
                            goodsList[index].rate,
                            goodsList[index].name);
                      },
                      behavior: HitTestBehavior.opaque,
                    )
                  ],
                ),
              ),
            ],
          ),
          elevation: 0.3,
        ),
      ),
      onTap: () {
        Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
          return new BrandGoodsPage(
            dis: "1",
            type: goodsList[index].brand_id,
            cat_name: goodsList[index].name,
          );
        }));
      },
    );
  }

  loadList2(
      String goods_brand_id, String desc, String rate, String name) async {
    Map map = new Map();
    map['p'] = page.toString();
    map['per'] = "4";
    map['token']=token;
    map['goods_brand_id'] = goods_brand_id;
    Response<String> response =
        await HttpUtil().post(Api.BaseUrl+"/index.php/wap/Goods/getShareList", data: getSign(map));
    Map userMap = json.decode(response.data);
    Navigator.of(context).pop(1);
    if (userMap['code'] == 1 && mounted) {
      GoodsListEntity bannerEntity = new GoodsListEntity.fromJson(userMap);
          print(bannerEntity.data.datas.length);

      if (bannerEntity.data.datas.length < 4) {
        Fluttertoast.showToast(msg: "素材不足，不能分享");
        return;
      }
      List<String> strings = new List();
      List<String> strings2 = new List();
      List<String> strings3 = new List();
      for (int i = 0; i < bannerEntity.data.datas.length && i < 4; i++) {
        strings.add(bannerEntity.data.datas[i].img.contains("http")?bannerEntity.data.datas[i].img:Api.ImgBaseUrl + bannerEntity.data.datas[i].img);
        strings2.add(bannerEntity.data.datas[i].price);
        strings3.add(bannerEntity.data.datas[i].old_price);
      }
      Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
        return new SharePinPaiPicPage(
          pics: strings,
          prices1: strings2,
          prices2: strings3,
          name: name,
          goods_id: goods_brand_id,
          goods_name: rate + desc,
        );
      }));
    }
  }
}
